<link rel="import" href="../polymer/polymer.html">

<dom-module id="chops-signin-aware">
  <template>
  </template>
</dom-module>
<script>
'use strict';
// This component adapts chops-signin to an API that is more familiar to Polymer
// components. Use this table to convert from google-signin-aware:

// google-signin-aware                    chops-signin-aware
//                         *events*
// google-signin-aware-success            user-update
// google-signin-aware-signed-out         user-update
// signed-in-changed                      user-update
//                         *properties*
// signedIn                               signedIn
// (getAuthResponse())                    authHeaders
// clientId                               (set window.AUTH_CLIENT_ID)
// scopes                                 (not supported)
// height                                 (not supported)
// theme                                  (not supported)
// (user.getBasicProfile())               profile

class ChopsSigninAware extends Polymer.Element {
  static get is() {
    return 'chops-signin-aware';
  }

  static get properties() {
    return {
      authHeaders: {type: Object, notify: true, readOnly: true},
      profile: {type: Object, notify: true, readOnly: true},
      signedIn: {type: Boolean, notify: true, readOnly: true},
    };
  }

  constructor() {
    super();
    this.updateProperties_();
  }

  connectedCallback() {
    // removeEventListener requires exactly the same function object that was
    // passed to addEventListener, so bind the listener methods.
    this.onUserUpdate_ = this.onUserUpdate_.bind(this);
    this.onHeadersReloaded_ = this.onHeadersReloaded_.bind(this);
    window.addEventListener('user-update', this.onUserUpdate_);
    window.addEventListener(
        'authorization-headers-reloaded', this.onHeadersReloaded_);
    this.onUserUpdate_();
  }

  disconnectedCallback() {
    window.removeEventListener('user-update', this.onUserUpdate_);
    window.removeEventListener(
        'authorization-headers-reloaded', this.onHeadersReloaded_);
  }

  updateProperties_() {
    // Use private setters because these properties are read-only to prevent
    // clients from accidentally overwriting them.
    this._setProfile(window.getUserProfileSync());
    this._setAuthHeaders(window.getAuthorizationHeadersSync());
    this._setSignedIn(!!this.profile);
  }

  onHeadersReloaded_(event) {
    this.updateProperties_();
  }

  onUserUpdate_() {
    this.updateProperties_();
    this.dispatchEvent(new CustomEvent('user-update'));
  }
}

customElements.define(ChopsSigninAware.is, ChopsSigninAware);
</script>
